package edu.fiu.cis.personalize.server.util;

import java.util.ArrayList;
import java.util.HashMap;

public class PajekFileGenerator {
	private ArrayList<V> vertices = new ArrayList<V>();
	private ArrayList<E> edges = new ArrayList<E>();
	private ArrayList<E> arcs = new ArrayList<E>();
	private HashMap<String, V> vMap = new HashMap<String, V>();
	private int counter;

	public PajekFileGenerator() {
		super();
	}

	private static class V {
		int id;
		String label;
		double value;
		String color;

		V(int id, String label, String color, double value) {
			this.label = label;
			this.id = id;
			this.color = color;
			this.value = value;

		}

		@Override
		public String toString() {
			return id + "  " + "\"" + label + "\"  " + format(value) + "  ic "
					+ color;
		}

	}

	private static final double PRECISION = 10000.0;

	public static double format(double v) {
		int i = (int) (v * PRECISION);
		return i / PRECISION;
	}

	private static class E {
		int start;
		int end;
		double value;

		E(int s, int e, double value) {
			this.start = s;
			this.end = e;
			this.value = value;
		}

		@Override
		public String toString() {
			return start + "  " + end + "  " + format(value);
		}
	}

	public String getResult() {
		StringBuffer sb = new StringBuffer();
		sb.append("*vertices ").append(vertices.size()).append("\r\n");
		for (V v : vertices) {
			sb.append(v).append("\r\n");
		}

		if (!edges.isEmpty()) {
			sb.append("*edges").append("\r\n");

			for (E e : edges) {
				sb.append(e).append("\r\n");
			}
		}
		if (!arcs.isEmpty()) {
			sb.append("*arcs").append("\r\n");
			for (E e : arcs) {
				sb.append(e).append("\r\n");
			}
		}

		return sb.toString();
	}

	public int addVertex(String label, double weight, String color) {
		V v = vMap.get(label);
		if (v == null) {
			v = new V(++counter, label, color, weight);
			vertices.add(v);
			vMap.put(label, v);
		}
		return v.id;
	}

	public V getVertex(String label) {
		return vMap.get(label);
	}

	public void addEdge(String from, String to, double weight) {
		_addE(edges, from, to, weight);
	}

	public void addArc(String from, String to, double weight) {
		_addE(arcs, from, to, weight);
	}

	private void _addE(ArrayList<E> l, String from, String to, double weight) {
		V f = vMap.get(from);
		V t = vMap.get(to);
		l.add(new E(f.id, t.id, weight));
	}

}
